﻿using CaltechSoft.Service.EntityFW.Entity;
using CaltechSoft.Service.Infrastructure.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CaltechSoft.Service.Repositories
{
    public class ProcedureRepository : BaseRepository<Procedure>
    {
        public override async Task<int> Add(Procedure entity)
        {
            Guard.Against<Exception>(string.IsNullOrWhiteSpace(entity.ProcedureName), "Procedure Name can not be null!");
            var removeItems = entity.Items.Where(n => !(n.StandardId > 0)).ToList();
            foreach (var item in removeItems)
            {
                entity.Items.Remove(item);
            }
            using (var context = Context)
            {
                var existingItem = context.Set<Procedure>().FirstOrDefault(n => n.ProcedureName == entity.ProcedureName.Trim());
                Guard.Against<Exception>(existingItem != null, "Duplicated ProcedureName is not allowed!");

                foreach (var item in entity.Items)
                {
                    if (item.StandardId > 0)
                    {
                        context.ProcedureItem.Add(item);
                    }
                }

                context.Procedures.Add(entity);
                return await context.SaveChangesAsync();
            }
        }

        public override async Task<int> Update(Procedure entity)
        {
            Guard.Against<Exception>(string.IsNullOrWhiteSpace(entity.ProcedureName), "Procedure Name can not be null!");
            try
            {
                using (var context = Context)
                {
                    var existingItem = context.Set<Procedure>().FirstOrDefault(n => n.ProcedureName == entity.ProcedureName.Trim() && n.Id != entity.Id);
                    Guard.Against<Exception>(existingItem != null, "Duplicated ProcedureName is not allowed!");

                    var attachedEntity = context.Procedures.FirstOrDefault(x => x.Id == entity.Id);

                    context.ProcedureItem.RemoveRange(attachedEntity.Items);

                    foreach (var item in entity.Items)
                    {
                        if (item.StandardId > 0)
                        {
                            item.ProcedureId = entity.Id;
                            context.ProcedureItem.Add(item);
                        }
                    }
                    await context.SaveChangesAsync();
                    return await base.Update(entity);
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
    }
}
